//
//  HomeVideoClassCell.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/16.
//

import UIKit
import AVKit
import AVFoundation
class HomeVideoClassCell: UITableViewCell {
    var dataSource:[VideoHistoryModel] = []
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = Theme.color.main
        view.allRound(3)
        return view
    }()
    
    lazy var titleLb: UILabel = {
        let label = UILabel()
        label.font = UIFont.pingFangSCRegular(ofSize: 15)
        label.textColor = Theme.color.main
        label.text = "视频广场"
        return label
    }()
    
    lazy var descLb: UILabel = {
        let label = UILabel()
        label.font = UIFont.pingFangSCRegular(ofSize: 11)
        label.textColor = Theme.color.text_d3
        label.text = "输入文案，一键生成视频"
        return label
    }()
    
    lazy var moreBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "更多"
        button.imageForNormal = UIImage(named: "icon_Mine_更多")
        button.titleColorForNormal = Theme.color.text_d3
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 12)
        button.isHidden = true
        return button
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
      
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        // 设置每行的项目数量
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(cellWithClass: HomeVideoItemCell.self)
        collectionView.backgroundColor = UIColor.clear // 设置背景颜色
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        moreBtn.layoutButtonWithEdgeInsetsStyle(.Right, space: 4)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        
        contentView.addSubviews([lineView, titleLb, descLb, moreBtn, collectionView])
        
        lineView.snp.makeConstraints { make in
            make.top.equalTo(30)
            make.leading.equalToSuperview().offset(16)
            make.width.equalTo(6)
            make.height.equalTo(16)
        }
        
        titleLb.snp.makeConstraints { make in
            make.centerY.equalTo(lineView)
            make.leading.equalTo(lineView.snp.trailing).offset(8)
        }
        
        descLb.snp.makeConstraints { make in
            make.bottom.equalTo(titleLb.snp.bottom)
            make.leading.equalTo(titleLb.snp.trailing).offset(5)
        }
        
        moreBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLb)
            make.trailing.equalToSuperview().offset(-16)
            make.height.equalTo(30)
        }
        let height = (SCREEN_WIDTH - 52) / 2
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(height+40)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setup(list:[VideoHistoryModel]){
        self.dataSource = list
        self.collectionView.reloadData()
    }
    
    
}
extension HomeVideoClassCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = dataSource[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withClass: HomeVideoItemCell.self, for: indexPath)
        cell.setup(model: model)
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height = (SCREEN_WIDTH - 52) / 2
        return CGSize(width: Int(height), height: Int(height + 40))
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = dataSource[indexPath.item]
        if let url = URL(string: model.video_url ?? "") {
            NDProgressHUD.showLoading()
            playVideo(from: url)
        }
    }
    func configureAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, options: [])
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("Failed to set audio session category. Error: \(error)")
        }
    }

    func playVideo(from url: URL) {
        configureAudioSession()
        let player = AVPlayer(url: url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        // 添加观察者以监控视频是否准备好播放
        player.addObserver(self, forKeyPath: "status", options: [.new, .initial], context: nil)
        // Present the AVPlayerViewController
        self.parentViewController?.present(playerViewController, animated: true) {
            player.play()
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" {
            if let player = object as? AVPlayer {
                if player.status == .readyToPlay {
                    // 视频准备好播放，隐藏加载框
                    NDProgressHUD.hide()
                    player.removeObserver(self, forKeyPath: "status")
                } else if player.status == .failed {
                    // 视频加载失败，隐藏加载框并显示错误
                    NDProgressHUD.hide()
                    print("Failed to load video")
                    player.removeObserver(self, forKeyPath: "status")
                }
            }
        }
    }
}



class HomeVideoItemCell: UICollectionViewCell {
    
    private lazy var iconIV: UIImageView = {
        let imageView = UIImageView()
        imageView.allRound(4)
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.clipsToBounds = true
        imageView.backgroundColor = UIColor(hexString: "#25262B")
        return imageView
    }()
      
    lazy var playIV: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_home_videoplayer")
        imageView.contentMode = .scaleToFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        contentView.addSubviews([iconIV, playIV])
        contentView.allRound(8)
        iconIV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        playIV.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
        }
    }
    
    func setup(model:VideoHistoryModel){
        iconIV.sd_setImage(with: URL(string: model.cover_url ?? ""))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}
